<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.Date" %>
<%@ page import = "java.text.SimpleDateFormat" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Enrollment Add</title>
<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
<link rel="stylesheet" type="text/css" href="css/student-system.css" /> 
<style type="text/css">
	td:nth-child(odd) {
		font-weight: bold;
	}
	.silvergrad:hover {
	    cursor: pointer;
	}
	a {
      text-decoration:none;
   	}
</style>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>

	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
<script>
	var count_course = 0;

	
	$(document).ready(function(){
		count_course = $('#count_course').val();
		//alert("count_course "+count_course);///////////////////////////////////////
		
		$('#save').hide();
		
		if(count_course == 0) {
			$('#save').hide();
			$('#bot-content').hide();
		}		
		$("#frm_add_file").hide();
		 $("#import_excel").click(function(){
			 
						$("#frm_add_file").toggle();
			 
		 });
		

	});
	
	function search_name(id,num) {	
		
		if($('#namelist').find('option').length > 0) {
			
			$('#namelist').find('option').remove();
		}
		if($('#namelist2').find('option').length > 0) {
			
			$('#namelist2').find('option').remove();
		}
		
		if(id != "") {
			id = id.toUpperCase();
			curriculum_id = $('#curriculum_id').val();
			
			/* AJAX */
			var xmlhttp;
			
			if(window.XMLHttpRequest) {
				// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			}
			else {
				// code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			
			xmlhttp.onreadystatechange = function() {
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
					var jsonObj = JSON.parse(xmlhttp.responseText);
					
					if(jsonObj.length == 0) {
						// no data
					}
					else{
						for(i in jsonObj) {
							var text = jsonObj[i].courseId+" "+jsonObj[i].courseNameEN;
							var option = '<option value="'+text+'" >';
							
							if(num == 1) {
								$('#namelist').append(option);
							}
							else if(num == 2) {
								$('#namelist2').append(option);
							}
						}
					}
				}
			}
			
			xmlhttp.open("POST", "search_coursename.jsp?course_id="+id+"&num="+num+"&curriculum_id="+curriculum_id, true);
			xmlhttp.send();
		}			
	}
	
	function search_class(name,num) {
		//alert(name);////////try///////
		
		if($('#class').find('option').length > 0 && num == 1) {
					
			$('#class').find('option').remove();
		}
		if($('#class2').find('option').length > 0 && num == 2) {
			
			$('#class2').find('option').remove();
		}
		
		var id = name.substr(0,name.indexOf(' '));
		var course_name = name.substr(name.indexOf(' ')+1).trim();
		
		//alert(id);////////try///////
			
		/* AJAX */
		var xmlhttp;
		
		if(window.XMLHttpRequest) {
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else {
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
				var jsonObj = JSON.parse(xmlhttp.responseText);
				
				if(jsonObj.length == 0) {
					// no data
				}
				else{
					for(i in jsonObj) {
						var option = '';
						
						if(jsonObj[i].monday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':จันทร์ '+jsonObj[i].monday+'">จันทร์ '+jsonObj[i].monday+'</option>';
						}
						else if(jsonObj[i].tuesday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':อังคาร '+jsonObj[i].tuesday+'">อังคาร '+jsonObj[i].tuesday+'</option>';
						}
						else if(jsonObj[i].wednesday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':พุธ '+jsonObj[i].wednesday+'">พุธ '+jsonObj[i].wednesday+'</option>';
						}
						else if(jsonObj[i].thursday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':พฤหัสบดี '+jsonObj[i].thursday+'">พฤหัสบดี '+jsonObj[i].thursday+'</option>';
						}
						else if(jsonObj[i].friday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':ศุกร์ '+jsonObj[i].friday+'">ศุกร์ '+jsonObj[i].friday+'</option>';
						}
						else if(jsonObj[i].saturday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':เสาร์ '+jsonObj[i].saturday+'">เสาร์ '+jsonObj[i].saturday+'</option>';
						}
						else if(jsonObj[i].sunday != "-") {
							option = '<option value="'+jsonObj[i].class_id+':อาทิตย์ '+jsonObj[i].sunday+'">อาทิตย์  '+jsonObj[i].sunday+'</option>';
						}
						
						if(num == 1) {
							$('#class').append(option);
						}
						else if(num == 2) {
							$('#class2').append(option);
						}
					}
				}
			}
		}
		
		xmlhttp.open("POST", "search_class.jsp?course_id="+id, true);
		xmlhttp.send();
				
	}

	function addClass(num){
		var course_id;
		
		var select;
		var select_class;
		var class_add;
		var class_id;
		var day;
		var time;
		
		var enroll_type;
		var grade;
		
		if(num == 1) {
			course_id =  document.getElementById("course_id").value;
			
			select = document.getElementById("class");
			select_class = select.options[select.selectedIndex].value;
			class_add = select_class.substr(select_class.indexOf(':')+1);
			class_id = select_class.substr(0,select_class.indexOf(':'));
			day_temp = select_class.substr(select_class.indexOf(':')+1,select_class.indexOf(' ')-1);
			day = day_temp.substr(0,day_temp.indexOf(' '));
			time = select_class.substr(select_class.indexOf(' ')+1).trim();
			
			enroll_type = document.getElementById("enroll_type").value;
			grade = document.getElementById("grade").value;
		}
		else if(num == 2) {
			course_id =  document.getElementById("course_id2").value;
			
			select = document.getElementById("class2");
			select_class = select.options[select.selectedIndex].value;
			class_add = select_class.substr(select_class.indexOf(':')+1);
			class_id = select_class.substr(0,select_class.indexOf(':'));
			day_temp = select_class.substr(select_class.indexOf(':')+1,select_class.indexOf(' ')-1);
			day = day_temp.substr(0,day_temp.indexOf(' '));
			time = select_class.substr(select_class.indexOf(' ')+1).trim();
			
			enroll_type = document.getElementById("enroll_type2").value;
			grade = document.getElementById("grade2").value;
		}
		
		//alert(course_id+" "+day+" "+time+" "+enroll_type+" "+grade);//////////try////////////
		//alert("class_id "+class_id);//////////try////////////
		
		var error = "";
		
		if(course_id == null || course_id == ""){
			error = " รหัสวิชา";
		}
		if(select_class == "select"){
			error = " class";
		}
		
		if(error != "") {
			alert("กรุณาเลือก"+error+" ก่อนค่ะ");
		}
		else {
			if(check_class(day,time)) {						
				text = '<tr id="tr_course_add'+count_course+'">'
					+ '<td>'+course_id+'</td>'
					+ '<td>'+class_add+'</td>'
					+ '<td>'+enroll_type+'</td>'
					+ '<td>'+grade+'</td>'
					+ '<td><input type="image" src="image/delete_icon.png" height="30px" width="30px" onclick="delete_course('+count_course+')" /></td>'
					+ '</tr>';		
				
				input = '<input type="hidden" id="course_id_add'+count_course+'" value="'+course_id+'" >'
					+ '<input type="hidden" id="class_id_add'+count_course+'" value="'+class_id+'" >'
					+ '<input type="hidden" id="day_add'+count_course+'" value="'+day+'" >'
					+ '<input type="hidden" id="time_add'+count_course+'" value="'+time+'" >'
					+ '<input type="hidden" id="enroll_type_add'+count_course+'" value="'+enroll_type+'" >'
					+ '<input type="hidden" id="grade_add'+count_course+'" value="'+grade+'" >';
				
				$('#bot-content').show();
				$('#course_add').append(text);
				$('#bot-content').append(input);
				$('#save').show();
				
				count_course++;
				
				var elem = document.getElementById("count_course");
				elem.value = count_course;
				
				// remove data old of input
				if(num == 1) {
					$('#course_id').val('');
					$('#class').find('option').remove();
					$('#class').append('<option value="select">เลือก Class</option>');
				}
				else if(num ==2) {
					$('#course_id2').val('');
					$('#class2').find('option').remove();
					$('#class2').append('<option value="select">เลือก Class</option>');
				}
				
			}
			else {
				alert("ไม่สามารถลงทะเบียนรายวิชานี้ได้ค่ะ");
				
				// remove data old of input
				if(num == 1) {
					$('#course_id').val('');
					$('#class').find('option').remove();
					$('#class').append('<option value="select">เลือก Class</option>');
				}
				else if(num ==2) {
					$('#course_id2').val('');
					$('#class2').find('option').remove();
					$('#class2').append('<option value="select">เลือก Class</option>');
				}
			}
			
		}
	}
	
	function check_class(day, time) {
		day = day.trim();
		
		var time_in_start = time.substr(0,time.indexOf('-'));
		var hour_in_start = parseInt(time_in_start.substr(0,time_in_start.indexOf(':')));
		var minute_in_start = parseInt(time_in_start.substr(time_in_start.indexOf(':')+1));
		
		var time_in_end = time.substr(time.indexOf('-')+1).trim();
		var hour_in_end = parseInt(time_in_end.substr(0,time_in_end.indexOf(':')));
		var minute_in_end = parseInt(time_in_end.substr(time_in_end.indexOf(':')+1));
/*		
		alert("day "+day);
		alert("time_in_start"+time_in_start+"   hour_in_start"+hour_in_start+"   minute_in_start"+minute_in_start);/////////////////try////////////////
		alert("time_in_end"+time_in_end+"   hour_in_end"+hour_in_end+"   minute_in_end"+minute_in_end);/////////////////try////////////////
*/
		length = $('#course_add tr').length;
		
//		alert("length  "+length);/////////////////try////////////////
		
		if(length == 2) { // no data in table 
			return true;
		}
		else {
			// check time
			for(var i=0; i<length-2; i++) {
			//	alert("i  "+i);/////////////////try////////////////
				
				var day_add = $('#day_add'+i).val().trim();
				
/*				alert("day_add  "+day_add+":");/////////////////try////////////////
				alert("day  "+day+":");/////////////////try////////////////
*/				
				if(day_add == day) {
					var time_add = $('#time_add'+i).val();
					
//					alert("time_add : "+time_add);/////////////////try////////////////
					
					var time_start = time_add.substr(0,time_add.indexOf('-'));
					var hour_start = parseInt(time_start.substr(0,time_start.indexOf(':')));
					var minute_start = parseInt(time_start.substr(time_start.indexOf(':')+1));
					
					var time_end = time_add.substr(time_add.indexOf('-')+1).trim();
					var hour_end = parseInt(time_end.substr(0,time_end.indexOf(':')));
					var minute_end = parseInt(time_end.substr(time_end.indexOf(':')+1));
/*					
					alert("time_start"+time_start+"  hour_start"+hour_start+"   minute_start"+minute_start);/////////////////try////////////////
					alert("time_end"+time_end+"  hour_end"+hour_end+"   minute_end"+minute_end);/////////////////try////////////////
					alert("hour_in_end"+hour_in_end+"   hour_start"+hour_start);/////////////////try////////////////
					alert(hour_in_start+" < "+hour_start+"   "+(hour_in_start < hour_start));/////////////////try////////////////
					alert(hour_in_end +" > "+hour_start+"   "+(hour_in_end > hour_start));/////////////////try////////////////
*/			
					if(hour_in_start > hour_start && hour_in_start < hour_end) {						
						return false;
					}
					if (hour_in_start > hour_start && hour_in_start < hour_end) {
						// true
					}
					if (hour_in_start < hour_start && hour_in_end <= hour_end) {
						// true
					}
					if (hour_in_start < hour_start && hour_in_end > hour_start) {
						return false;
					}
					if (hour_in_start == hour_start) {
						return false;
					}
				}
				
			}// end for
			
			return true;
		}
		

	}
	

	function delete_course(id) {
		
		$('#tr_course_add'+id).remove();
		$('#course_id_add'+id).remove();
		$('#class_id_add'+id).remove();
		$('#day_add'+id).remove();
		$('#time_add'+id).remove();
		$('#enroll_type_add'+id).remove();
		$('#grade_add'+id).remove();
		
		count_course--;
		
		
		if(id == 0) {
			$('#save').hide();
			$('#bot-content').hide();
		}
		else {
			for(var i=count_course; i>id; i--) {				
				var tr_course_add = document.getElementById("tr_course_add"+i);
				tr_course_add.setAttribute("id", "tr_course_add"+(i-1));  // using .setAttribute() method
				
				var course_id_add = document.getElementById("course_id_add"+i);
				course_id_add.setAttribute("id", "course_id_add"+(i-1));  // using .setAttribute() method
				
				var class_id_add = document.getElementById("class_id_add"+i);
				class_id_add.setAttribute("id", "class_id_add"+(i-1));  // using .setAttribute() method
				
				var day_add = document.getElementById("day_add"+i);
				day_add.setAttribute("id", "day_add"+(i-1));  // using .setAttribute() method
				
				var time_add = document.getElementById("time_add"+i);
				time_add.setAttribute("id", "time_add"+(i-1));  // using .setAttribute() method
				
				var enroll_type_add = document.getElementById("enroll_type_add"+i);
				enroll_type_add.setAttribute("id", "enroll_type_add"+(i-1));  // using .setAttribute() method
				
				var grade_add = document.getElementById("grade_add"+i);
				grade_add.setAttribute("id", "grade_add"+(i-1));  // using .setAttribute() method
							
			}		
		}
		
		
		var elem = document.getElementById("count_course");
		elem.value = count_course;
	}
	
	function save() {
		var student_id = $('#student_id').val();
		var num_old_add = $('#num_old_add').val();
		
		//alert("count_course "+count_course);///////////////////////////////////////
		//alert("num_old_add "+num_old_add);///////////////////////////////////////
		
		var parameter = 'student_id='+student_id+'&count_course='+ (count_course-num_old_add);
		
		var i;
	/*	if(num_old_add == "null") {
			i = 0;
			
			//parameter = parameter + '&start_add=0';
		}
		else {
	*/		i = parseInt(num_old_add);
			
			//parameter = parameter + '&start_add='+i;
	//	}
		
		//alert("i "+i);
		
		for(i, j=0; i<count_course; i++, j++) {
			//alert("i in for "+i);
			
			var class_id = $('#class_id_add'+i).val();
			var enroll_type = $('#enroll_type_add'+i).val();
			var grade = $('#grade_add'+i).val();
			
			parameter = parameter + '&class_id_' + j + '=' + class_id
						+ '&enroll_type_' + j + '=' + enroll_type
						+ '&grade_'+ j + '=' + grade;
		}
		
		//alert(parameter);/////try//////
		
		/* AJAX */
		var xmlhttp;
		
		if(window.XMLHttpRequest) {
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else {
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var result = xmlhttp.responseText.trim();
				if(result == "success"){
					alert("บันทึกข้อมูลสำเร็จ");
					document.location.href = "enroll_enrollment.jsp";
				}else if(result == "fail"){
					alert("บันทึกข้อมูลผิดพลาด กรุณาลองใหม่อีกครั้ง");
					document.location.href = "enroll_enrollment.jsp";
				}				
			}
		}
	
		xmlhttp.open("POST", "enroll_enrollment_add_save.jsp?"+parameter, true);
		xmlhttp.send();
	}
	
	
	
	function isValidUploadForm(oForm){
		
		//alert("Active isValidUploadForm");
		
		var _validFileExtensions = [".xlsx", ".xls"];
		  var arrInputs = oForm.getElementsByTagName("input");
		 
		  
		//  alert("arrInputs:"+ oForm.getElementsByTagName("input")[0].value);
		  
		  var file_name =  oForm.getElementsByTagName("input")[0].value
		  	if(file_name=="")
		  	{
		  		alert("กรุณาเลือกไฟล์ที่จะทำการ Import ในรูปแบบ xls, xlsx");
		  		return false;
		  	}
		  
		    for (var i = 0; i < arrInputs.length; i++) {
		        var oInput = arrInputs[i];
		        if (oInput.type == "file") {
		            var sFileName = oInput.value;
		            if (sFileName.length > 0) {
		                var blnValid = false;
		                for (var j = 0; j < _validFileExtensions.length; j++) {
		                    var sCurExtension = _validFileExtensions[j];
		                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
		                        blnValid = true;
		                        break;
		                    }
		                }

		                if (!blnValid) {
		                    alert("เกิดข้อผิดพลาด " + sFileName + " ไฟล์ที่แนบไม่ตรงรูปแบบของ : " + _validFileExtensions.join(", "));
		                    return false;
		                }
		            }
		        }
		    }

		    return true;
		
		
		
	}
	
	function show_grade(value,id) {
		if(value == "AU") {

			text = '<option value="P">P</option>'
				+ '<option value="S">S</option>'
				+ '<option value="T">T</option>'
				+ '<option value="U">U</option>'
				+ '<option value="W">W</option>';
				
			if(id == 1) {
				$('#grade').find('option').remove();
				
				$('#grade').append(text);
			}
			else {
				$('#grade2').find('option').remove();
				
				$('#grade2').append(text);
			}
		}
		else {
			text = '<option value="X">X</option>'
				+ '<option value="A">A</option>'
				+ '<option value="B+">B+</option>'
				+ '<option value="B">B</option>'
				+ '<option value="C+">C+</option>'
				+ '<option value="C">C</option>'
				+ '<option value="D+">D+</option>'
				+ '<option value="D">D</option>'
				+ '<option value="F">F</option>'
				+ '<option value="P">P</option>'
				+ '<option value="S">S</option>'
				+ '<option value="T">T</option>'
				+ '<option value="U">U</option>'
				+ '<option value="W">W</option>';
				
			if(id == 1) {
				$('#grade').find('option').remove();
				
				$('#grade').append(text);
			}
			else {
				$('#grade2').find('option').remove();
				
				$('#grade2').append(text);
			}
			
		}
	}

</script>

</head>
<body>
<%
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	//get permission 
	
		String name = String.valueOf(session.getAttribute("name"));
		String surname = String.valueOf(session.getAttribute("surname"));
		String role_name = String.valueOf(session.getAttribute("enrollment_role"));
		
		String department_id = String.valueOf(session.getAttribute("department_id"));

		
				
		System.out.println("name : " + name);///////////////////////////////
		System.out.println("department_id : " + department_id);/////////////////////////
		
		
		List<String> system_name = new ArrayList<String>();
		
		Permission permission = new Permission(strUser,name);
		permission.setDepartmentId(department_id);
		permission.setRegisCreate(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_create"))));
		permission.setRegisDelete(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_delete"))));
		permission.setRegisRead(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_read"))));
		permission.setRegisUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_update"))));
		
		//check permission
		if(!permission.getRegisCreate()){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp"> 	
		<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	/* find department in database */
	List<Department> department = new ArrayList<Department>();
	
	try {			   
		ResultSet rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
				+ " FROM department " + " ORDER BY department_id");
		
		while(rs_department.next()) {
			Department dep = new Department();
			
			dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
			dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
			
			department.add(dep);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	String student_id = request.getParameter("student_id");
	System.out.println("@ enroll_enrollment_add:"+student_id);//////////////try///////////////

	Date date = new Date();
	int current_year = date.getYear()+1900;
	int temp_year = date.getYear()+1900;
	int current_month = date.getMonth()+1;
	Student stu = new Student();
	String current_semester = "0";
	String curriculum_id = "0";
	
	if(current_month>=8 && current_month<=12)
	{
		current_semester = "1";
		
	}else if(current_month>=1&&current_month<=5){
	
		current_semester = "2";
		
		current_year = current_year-1;
		
	}else if (current_month>=6&&current_month<=7){
		
		current_semester = "3";
		
		current_year = current_year-1;
		
	}
	
	
	ResultSet rs = 
			connect.createStatement().executeQuery(" SELECT S.picture, N.title_th ,"+
					" N.name_th, N.surname_th , N.name_en , N.surname_en ,P.personal_id, P.gender,P.marital_status ,"+
				    " P.address , P.phone_number, P.email , P.facebook , S.father_name , S.father_address ,"+
					" S.father_phone ,S.mother_name , S.mother_address , S.mother_phone , S.parent_name,"+
				    " S.parent_address ,S.parent_phone ,S.student_id, S.start_date , S.entrance_id  , S.school ,"+
					" S.gpa , ST.status_name ,D.department_name_th, S.curriculum_id ,P.date_of_birth ,S.lecturer_id, S.curriculum_id "+
				    " FROM student S, full_name N, department D, status ST, people P "+
				    " WHERE S.index = P.index AND P.full_name_id = N.full_name_id "+
				    " AND S.department_id = D.department_id AND S.status_id = ST.status_id "+
				    " AND S.student_id='"+student_id+"'");
	while(rs.next())
	{
		//stu.setPicture(rs.getString("picture"));
		String src_path_full = rs.getString("picture");
		if((src_path_full!=null)&&(!("null").equals(src_path_full)))
		{
			String[] src_path_temp = src_path_full.split("/");	
			int length = src_path_temp.length;
			
			String src_path_a = src_path_temp[length-2];
			String src_path_b = src_path_temp[length-1];
			
			String src_path = src_path_a+"/"+src_path_b;
			
			stu.setPicture(src_path);
		
		}else{
			stu.setPicture("upload/default_person_icon.jpg");
			
		}		
		
		stu.setNameTH(rs.getString("name_th"));
		stu.setSurnameTH(rs.getString("surname_th"));
		Date start_date = new SimpleDateFormat("yyyy-MM-dd").parse(rs.getString("start_date"));
		int start_date_num = start_date.getYear()+1900;
		String year_str ;
	
		curriculum_id = rs.getString("curriculum_id");
	
	
		if(current_month<6)
		{
			
			year_str =(temp_year-start_date_num) + "";
			
		}else{
		
			year_str =(temp_year-start_date_num+1)+"";
		}
		
		stu.setYear(year_str);
		stu.setDepartment(rs.getString("department_name_th"));
		stu.setStudentId(rs.getString("student_id"));
	}
	
	List<CClass> cclass = new ArrayList<CClass>();
	System.out.println("current_year:"+current_year);//////////////try///////////////
/*	System.out.println("sql_statement:"+" SELECT C.class_id , C.course_id ,"+
			" C.index , C.year , C.semester , C.room , C.monday,"+
			" C.tuesday, C.wednesday , C.thursday, C.friday , C.saturday,"+
			" C.sunday , D.course_name_th"+
			" FROM class C , course D"+
			" WHERE C.year='"+current_year+"'" +
			" AND C.semester='"+current_semester+"'"+
			" AND D.course_id=C.course_id");//////////////try///////////////
	ResultSet rs_class =  
			connect.createStatement().executeQuery(" SELECT C.class_id , C.course_id ,"+
							" C.index , C.year , C.semester , C.room , C.monday,"+
							" C.tuesday, C.wednesday , C.thursday, C.friday , C.saturday,"+
							" C.sunday , D.course_name_th"+
							" FROM class C , course D"+
							" WHERE C.year='"+current_year+"'" +
							" AND C.semester='"+current_semester+"'"+
							" AND D.course_id=C.course_id");
	while(rs_class.next()){
		
		CClass cls = new CClass();
		cls.setClass_id(rs_class.getString("class_id"));
		cls.setCourse_id(rs_class.getString("course_id"));
		cls.setLecturer_id(rs_class.getString("index"));
		cls.setYear(rs_class.getString("year"));
		cls.setSemester(rs_class.getString("semester"));
		cls.setRoom(rs_class.getString("room"));
		cls.setMonday(rs_class.getString("monday"));
		cls.setTuesday(rs_class.getString("tuesday"));
		cls.setWednesday(rs_class.getString("wednesday"));
		cls.setThursday(rs_class.getString("thursday"));
		cls.setFriday(rs_class.getString("friday"));
		cls.setSaturday(rs_class.getString("saturday"));
		cls.setSunday(rs_class.getString("sunday"));
		cls.setCourse_name_th(rs_class.getString("course_name_th"));
		cclass.add(cls);
	}
	
	System.out.println("cclass found :"+cclass.size());
*/	
	// find enrollment in DB
	int count = 0;
	try {
		String sql_enroll = "SELECT DISTINCT E.grade, E.type_of_enrollment, C.course_id, C.course_name_en, E.class_id "
						+ " , CL.monday, CL.tuesday, CL.wednesday, CL.thursday, CL.friday, CL.saturday, CL.sunday "
						+ " FROM enrollment E, course_name C, class CL "
						+ " WHERE E.class_id=CL.class_id AND C.course_id=CL.course_id "
						+ " AND CL.year='"+current_year+"' AND CL.semester='"+current_semester+"' "
						+ " AND E.student_id='"+stu.getStudentId()+"'";
		
		System.out.println("sql enroll : "+sql_enroll);
		
		ResultSet rs_enroll = connect.createStatement().executeQuery(sql_enroll);
		
		while(rs_enroll.next()) {
			CClass cl = new CClass();
			
			cl.setGrade(rs_enroll.getString("grade"));
			cl.setType(rs_enroll.getString("type_of_enrollment"));
			cl.setCourse_id(rs_enroll.getString("course_id"));
			cl.setCourse_name_th(rs_enroll.getString("course_name_en"));
			cl.setClass_id(rs_enroll.getString("class_id"));
			cl.setMonday(rs_enroll.getString("monday"));
			cl.setTuesday(rs_enroll.getString("tuesday"));
			cl.setWednesday(rs_enroll.getString("wednesday"));
			cl.setThursday(rs_enroll.getString("thursday"));
			cl.setFriday(rs_enroll.getString("friday"));
			cl.setSaturday(rs_enroll.getString("saturday"));
			cl.setSunday(rs_enroll.getString("sunday"));
			
			cclass.add(cl);
		}
		
		count = cclass.size();
		
		System.out.println("size : "+count);
	} catch(SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
%>


<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
				
				<div id="main-content-ac">		
				
					 <div style="padding-left: 960px;">
							<table style="border: 0px;">
								<tr style="border: 0px;">
									<td style="border: 0px;" class="silvergrad" id="import_excel">
										<br>
										<br> <br>
										<span title="Import By Excel"><img src="image/excel_import_icon.png" style="width:60px;height:60px;" ></span>
							
									</td>
									<td style="border: 0px;">
										</br>
										</br>
								
										<div class="imageFrame" style="font-size: 15px;">นำเข้าข้อมูลย้อนหลัง </div>
									</td>
								</tr>	
							</table>
					 </div>
					 		<div id="frm_add_file">
								<center>
											<table>
												<tr>
													<td>
														<center>
															 <form method="post" onsubmit="return isValidUploadForm(this);	" action="UploadServletEnrollOld"enctype="multipart/form-data">
									        		  			 เลือกไฟล์ <input id="file_box" type="file" name="uploadFile"> 
									        		  			 <br>
									        		  			 <br>
									        		  			 <br>
									        		  			 <input type="hidden" name="student_id" value="<%=stu.getStudentId() %>">
									        		  			 <input type="submit" value="Upload" />
									        		  			 
									        		  			 <br>
									        		  			 </form>
									        		  			 
									        		  	</center>
									        		 </td>
									        		 
							        		  		 
												</tr>
													
											</table>
									</center>		
				
							</div>
					 
					 
							
						<br><br>
					<div id="top-content" style="background-color: #e2e0e0;">
						<br><br>
							<center>
								<table  style="font-size:20px;background-color: #f2f0f0;">
									<tr>
										<td width="50" height="10" rowspan="2" style="text-align: center;">
											<% 
											  
											  	System.out.println("PICTURE:"+stu.getPicture());
												if(stu.getPicture()==null)
												{
														System.out.println(" PICTURE NULL");
											  %>
													 
											 			<img id="student_image" src="upload/default_person_icon.jpg" style="width:130px;height:160px;	">
											  <% 													
												}
												else{
													System.out.println(" PICTURE NOT NULL");
													
											   %>					
														 <img id="student_image" src="<%=stu.getPicture() %>" style="width:130px;height:160px;">
											   <%
												}
											  
											  %>					        		
						        		
						        	
										</td>
										 <td height="10">
									             	
									                	<%=stu.getNameTH()+" "+stu.getSurnameTH() %>					          		
									     </td>
									     <td height ="10">
									     			<%=stu.getDepartment() %>
									     </td>
									</tr>
									<tr>
										<td height="10">
													<%=stu.getStudentId() %>
													<input type="hidden" id="student_id" value="<%=stu.getStudentId() %>"/>
													<input type="hidden" id="curriculum_id" value="<%=curriculum_id %>"/>
										</td>
										 <td height="10">
									               ชั้นปี <%=stu.getYear() %> &nbsp; เทอม <%=current_semester %>
									     </td>
										
									</tr>
								     
								</table>
							</center>
							<br><br>
					</div>
						<br><br>
					
					<div id="mid-content"  style="background-color: #e2e0e0;">
						<br><br>
							<center>
								<table  style="font-size:20px; background-color: #f2f0f0;">
										<tr>
											<td>
												วิชาในหลักสูตร <input type="text" name="course_id" id="course_id" value="" list="namelist" onkeyup="search_name(this.value,'1')" onchange="search_class(this.value,'1')" required>
												<datalist id="namelist">
							  					</datalist>
											</td>
											
											<td>
												class <select name="class" id="class" style="width:200px;" required>
								 					<option value="select">เลือก Class</option>
								 					
							  		
												</select>
												
											</td>
											<td>
												รูปแบบการลงทะเบียน <select name="enroll_type" id="enroll_type"  onchange="show_grade(this.value,'1')">
														<option value="N">NORMAL</option>
														<option value="AU">AUDIT</option>
														<option value="A">ADD</option>
												</select>
											</td>
											<td>
												เกรด <select name="grade" id="grade">
														<option value="X">X</option>
														<option value="A">A</option>
														<option value="B+">B+</option>
														<option value="B">B</option>
														<option value="C+">C+</option>
														<option value="C">C</option>
														<option value="D+">D+</option>
														<option value="D">D</option>
														<option value="F">F</option>
														<option value="P">P</option>
														<option value="S">S</option>
														<option value="T">T</option>
														<option value="U">U</option>
														<option value="W">W</option>
												</select>
											</td>
											<td>
													<div style="cursor: pointer;">
														<img src="image/add_icon.png" width="25px" height="25px" onclick="addClass('1')">	
													</div>
											</td>
											
										</tr>
										
										<tr>
											<td>
												วิชานอกหลักสูตร <input type="text" name="course_id2" id="course_id2" value="" list="namelist2" onkeyup="search_name(this.value,'2')" onchange="search_class(this.value,'2')" required>
												<datalist id="namelist2">
							  					</datalist>
											</td>
											
											<td>
												class <select name="class2" id="class2" style="width:200px;" required>
								 					<option value="select">เลือก Class</option>
								 					
							  		
												</select>
												
											</td>
											<td>
												รูปแบบการลงทะเบียน <select name="enroll_type2" id="enroll_type2" onchange="show_grade(this.value,'2')">
														<option value="N">NORMAL</option>
														<option value="AU">AUDIT</option>
														<option value="A">ADD</option>
												</select>
											</td>
											<td>
												เกรด <select name="grade2" id="grade2">
														<option value="X">X</option>
														<option value="A">A</option>
														<option value="B+">B+</option>
														<option value="B">B</option>
														<option value="C+">C+</option>
														<option value="C">C</option>
														<option value="D+">D+</option>
														<option value="D">D</option>
														<option value="F">F</option>
														<option value="P">P</option>
														<option value="S">S</option>
														<option value="T">T</option>
														<option value="U">U</option>
														<option value="W">W</option>
												</select>
											</td>
											<td>
													<div style="cursor: pointer;">
														<img src="image/add_icon.png" width="25px" height="25px" onclick="addClass('2')">	
													</div>
											</td>
											
										</tr>
								</table>
								<br><br>
							</center>
					</div>
					<br><br>
					
					<div id="bot-content" style="background-color: #e2e0e0;">
						<br><br>
						<center>
							<table id="course_add" style="font-size:20px; background-color: #f2f0f0; width: 950px; text-align: center;">
								<tr>
									<td>รหัสวิชา</td>
									<td>class</td>
									<td>รูปแบบการลงทะเบียน</td>
									<td>เกรด</td>
									<td></td>
								</tr>
								
				<%
							int i = 0;
							for(CClass cl : cclass) {
				%>
								<tr>
									<td>
										<%=cl.getCourse_id()+" "+cl.getCourse_name_th() %>
									</td>
									<td>
				<%
									if(!"-".equals(cl.getMonday())) {
				%>
										<%="จันทร์ "+cl.getMonday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="จันทร์ " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getMonday() %>" >
				<%
									}
									else if(!"-".equals(cl.getTuesday())) {
				%>
										<%="อังคาร "+cl.getTuesday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="อังคาร " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getTuesday() %>" >
				<%			
									}
									else if(!"-".equals(cl.getWednesday())) {
				%>
										<%="พุธ "+cl.getWednesday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="พุธ " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getWednesday() %>" >
				<%			
									}
									else if(!"-".equals(cl.getThursday())) {
				%>
										<%="พฤหัสบดี "+cl.getThursday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="พฤหัสบดี " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getThursday() %>" >
				<%			
									}
									else if(!"-".equals(cl.getFriday())) {
				%>
										<%="ศุกร์ "+cl.getFriday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="ศุกร์ " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getFriday() %>" >
				<%			
									}
									else if(!"-".equals(cl.getSaturday())) {
				%>
										<%="เสาร์ "+cl.getSaturday() %>
										<input type="hidden" id="day_add<%=i %>" value="<%="เสาร์ " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getSaturday() %>" >
				<%			
									}
									else if(!"-".equals(cl.getSunday())) {
				%>
										<%="อาทิตย์ "+cl.getSunday()%>
										<input type="hidden" id="day_add<%=i %>" value="<%="อาทิตย์ " %>" >
										<input type="hidden" id="time_add<%=i %>" value="<%=cl.getSunday() %>" >
				<%			
									}
				%>
									</td>
									<td>
										<%=cl.getType() %>
									</td>
									<td>
										<%=cl.getGrade() %>
									</td>
									<td></td>
								</tr>
								
								<input type="hidden" id="course_id_add<%=i %>" value="<%=cl.getCourse_id()+" "+cl.getCourse_name_th() %>" >
								<input type="hidden" id="class_id_add<%=i %>" value="<%=cl.getClass_id() %>" >
								<input type="hidden" id="enroll_type_add<%=i %>" value="<%=cl.getType() %>" >
								<input type="hidden" id="grade_add<%=i %>" value="<%=cl.getGrade() %>" >
								
								
				<% 
								i++;
							}
				%>
							</table>
							
							<input type="hidden" id="count_course" value="<%= count%>">
				<%
						if(count > 0) {
				%>
							<input type="hidden" id="num_old_add" value="<%= count%>">
				<%
						}
						else {
				%>
							<input type="hidden" id="num_old_add" value="<%= 0%>">
				<%
						}
				%>
						</center>
						<br><br>
					</div>	
					
					<br><br>
					
					<div id="finish-content" style="background-color: #e2e0e0;">
						<br><br>
						<center>
							<table id="course_add" style="font-size:20px; background-color: #e2e0e0; width: 800px; text-align: center; border: 0px;">
								<tr>
									<td width="800px;"><button class="buttonStyle" id="save" onclick="save()">save</button></td>
									<td width="800px;"><a href="enroll_enrollment.jsp"><button class="buttonStyle">cancel</button></a></td>
								</tr>
							</table>
							
							
							<br><br>
						</center>
						
					</div>	
						
					<br><br><br><br>
				
				
			<div style="clear: both;"></div>				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
  </div>	
						

</body>
</html>